import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Layout, Tabs, List, Tag, Card, Button, Badge, Spin, message, Modal } from "antd";
const { Content } = Layout;
const { TabPane } = Tabs;
import axios from "axios";
import { getAuthToken } from "@/router";
import { mockRankings } from "@/pages/home";
import {
  CrownOutlined,
  TrophyOutlined,
  UploadOutlined,
  ClockCircleOutlined,
  HomeOutlined,
  SyncOutlined,
  QuestionCircleOutlined
} from "@ant-design/icons";
import "./ranking.styl";

const RankingPage = () => {
  const [activeRankTab, setActiveRankTab] = useState('upload');
  const [leaderboardData, setLeaderboardData] = useState(mockRankings);
  const [loading, setLoading] = useState(true);
  const [isAdmin, setIsAdmin] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [showHelpModal, setShowHelpModal] = useState(false); // 新增状态控制帮助弹窗
  const navigate = useNavigate();

  // 润色后的帮助内容
  const helpContent = (
    <div className="help-content">
      <h3><TrophyOutlined /> 排行榜与成就系统说明</h3>
      <p className="feature-item">
        <strong>实时更新双重排行榜：</strong>
        <ul>
          <li><Tag color="blue">上传量TOP10</Tag> - 统计用户为站点贡献的上传数据总量</li>
          <li><Tag color="green">保种时长TOP10</Tag> - 统计用户保持种子上传的累计时间</li>
        </ul>
      </p>
      <p className="feature-item">
        <strong><CrownOutlined /> 月度结算与奖励：</strong>
        <ul>
          <li>每月最后一天23:59进行结算</li>
          <li>结算完成后，榜单数据清零，次月重新计算</li>
          <li>榜单前3名分别获得1600、1200、800魔力值</li>
          <li>4-10名每人获得400魔力值</li>
          <li>所有上榜用户获得专属荣誉标识</li>
        </ul>
      </p>
      <p className="feature-item">
        <strong><ClockCircleOutlined /> 数据更新频率：</strong>
        每15分钟自动更新一次榜单数据
      </p>
    </div>
  );

  // 检查管理员权限
  const checkAdminPermission = async () => {
    try {
      const response = await axios.get('http://192.168.55.192:8080/api/admin/check', {
        headers: { Authorization: getAuthToken() }
      });
      setIsAdmin(response.data.data?.isAdmin || false);
    } catch (error) {
      console.error('权限检查失败:', error);
      setIsAdmin(false);
    }
  };

  // 刷新排行榜数据
  const handleRefresh = async () => {
    try {
      setIsRefreshing(true);
      const response = await axios.post(
        'http://192.168.55.192:8080/api/leaderboard/admin/refresh',
        null,
        { headers: { Authorization: getAuthToken() } }
      );
      
      if (response.data.code === 200) {
        message.success('排行榜刷新成功');
        // 刷新后重新获取数据
        await fetchData();
      }
    } catch (error) {
      console.error('刷新失败:', error);
      message.error(error.response?.data?.message || '刷新操作失败');
    } finally {
      setIsRefreshing(false);
    }
  };

  const fetchData = async () => {
    try {
      const [uploadRes, seedingRes] = await Promise.all([
        axios.get('http://192.168.55.192:8080/api/leaderboard/upload', {
          headers: { Authorization: getAuthToken() }
        }),
        axios.get('http://192.168.55.192:8080/api/leaderboard/seeding', {
          headers: { Authorization: getAuthToken() }
        })
      ]);

      setLeaderboardData({
        upload: uploadRes.data.code === 200 ? uploadRes.data.data : mockRankings.upload,
        seeding: seedingRes.data.code === 200 ? seedingRes.data.data : mockRankings.seeding
      });
    } catch (error) {
      console.error('排行榜加载失败，使用虚拟数据:', error);
      setLeaderboardData(mockRankings);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const init = async () => {
      await checkAdminPermission();
      await fetchData();
    };
    init();
  }, []);

  const getRankBadge = (index) => {
    const badges = [
      <CrownOutlined className="gold-icon" />,
      <TrophyOutlined className="silver-icon" />,
      <TrophyOutlined className="bronze-icon" />
    ];
    return badges[index] || <span className="rank-number">{index + 1}</span>;
  };

  const renderRankList = (data) => (
    <Spin spinning={loading} tip="加载排行榜数据...">
      <List
        dataSource={data}
        renderItem={(item, index) => (
          <List.Item
            className={`rank-item ${index < 3 ? 'rank-top-' + (index + 1) : ''}`}
            actions={[<Tag color="#722ed1">{item.scoreDisplay}</Tag>]}
          >
            <List.Item.Meta
              avatar={<Badge className="rank-badge" count={getRankBadge(index)} />}
              title={item.username}
              description={[<Tag>Lv.{item.userLevel}</Tag>]}
            />
          </List.Item>
        )}
      />
    </Spin>
  );

  return (
    <Layout className="ranking-layout">
      <Content className="ranking-content">
        <Button
          type="link"
          icon={<HomeOutlined />}
          onClick={() => navigate('/')}
          className="back-home"
        >
          返回首页
        </Button>

        <Card 
          title="全站排行榜" 
          className="full-ranking-card"
          extra={isAdmin && (
            <Button
              type="primary"
              icon={<SyncOutlined spin={isRefreshing} />}
              onClick={handleRefresh}
              disabled={isRefreshing}
            >
              {isRefreshing ? '刷新中...' : '强制刷新数据'}
            </Button>
          )}
        >
          <Tabs
            activeKey={activeRankTab}
            onChange={setActiveRankTab}
            animated
            tabBarGutter={32}
          >
            <TabPane
              key="upload"
              tab={
                <span className="tab-title">
                  <UploadOutlined />上传排行榜
                </span>
              }
            >
              {renderRankList(leaderboardData.upload)}
            </TabPane>
            <TabPane
              key="seeding"
              tab={
                <span className="tab-title">
                  <ClockCircleOutlined />保种排行榜
                </span>
              }
            >
              {renderRankList(leaderboardData.seeding)}
            </TabPane>
          </Tabs>
          <div className="ranking-footer">
            <Tag icon={<ClockCircleOutlined />} color="geekblue">
              数据每15分钟更新一次
            </Tag>
            <Tag icon={<CrownOutlined />} color="gold">
              每月最后一天23:59结算奖励
            </Tag>
            {isAdmin && (
              <Tag icon={<SyncOutlined />} color="volcano">
                管理员模式
              </Tag>
            )}
            {/* 添加帮助按钮 */}
            <Button 
              type="text" 
              icon={<QuestionCircleOutlined />} 
              onClick={() => setShowHelpModal(true)}
              style={{ marginLeft: 'auto' }}
            >
              帮助说明
            </Button>
          </div>
        </Card>
      </Content>
      
      {/* 帮助弹窗 */}
      <Modal
        title="排行榜规则说明"
        open={showHelpModal}
        onCancel={() => setShowHelpModal(false)}
        footer={[
          <Button type="primary" onClick={() => setShowHelpModal(false)}>
            我知道了
          </Button>
        ]}
        width={650}
      >
        {helpContent}
      </Modal>
    </Layout>
  );
};

export default RankingPage;